<?php
class weiUtil{
	//校验数据来源
	public function valid()
	{
		$echoStr = $_GET["echostr"];

		//valid signature , option
		if($this->checkSignature()){
			return true;
		}
		return false;
	}

	private function checkSignature()
	{
		$signature = $_GET["signature"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];

		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );

		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}


	/**
	 * 创建菜单
	 */
	public static function createMenu($menuPostString,$accessToken)
	{
		//$accessToken = $this->getAccessToken();//获取access_token
		//构造POST给微信服务器的菜单结构体
		$menuPostUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$accessToken;//POST的url
		$response = json_decode(weiUtil::dataPost($menuPostString, $menuPostUrl),true);//将菜单结构体POST给微信服务器
		return $response;
	}

	/**
	 * 删除菜单
	 */
	public static function deleteMenu($menuPostString,$accessToken)
	{
		//$accessToken = $this->getAccessToken();//获取access_token
		//构造POST给微信服务器的菜单结构体
		$menuPostUrl = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$accessToken;//POST的url
		$response = json_decode(weiUtil::dataPost($menuPostString, $menuPostUrl),true);//将菜单结构体POST给微信服务器
		return $response;
	}

	/**
	 * 获取菜单
	 */
	public function getMenu($menuPostString)
	{
		$accessToken = $this->getAccessToken();//获取access_token
		//构造POST给微信服务器的菜单结构体
		$menuPostUrl = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$accessToken;//POST的url
		$response = json_decode($this->dataPost($menuPostString, $menuPostUrl),true);//将菜单结构体POST给微信服务器
		return $response;
	}

	public static  function getAccessToken($appid,$secret)
	{
		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
		$json=weiUtil::http_request_json($url);
		$data=json_decode($json,true);
		if($data['access_token']){
			return $data['access_token'];
		}else{
			return "获取access_token错误";
		}
	}

	//因为url是https 所有请求不能用file_get_contents,用curl请求json 数据
	static function  http_request_json($url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$result = curl_exec($ch);
		curl_close($ch);
		return $result;
	}

	/**
	 * POST方式提交数据
	 */
	static function dataPost($post_string, $url) {
		//$context = array ('http' => array ('method' => "POST", 'header' => "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) \r\n Accept: */* ", "Content-type"=> "application/x-www-form-urlencoded ",'content' => $post_string ) );
		$context['http'] = array
		(
                'method' => 'POST',  
                'header' => "Connection: close ".
                "Content-type: application/x-www-form-urlencoded ",
                        'content' => $post_string,
		);

		$stream_context = stream_context_create ( $context );
		$data = file_get_contents ( $url, FALSE, $stream_context );
		return $data;
	}


	/**
	 * 回复文本信息
	 */
	static function responseText($fromUsername,$toUsername,$contentStr){
		$time = time();
		$textTpl ="<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime><![CDATA[%s]]></CreateTime>
			<MsgType><![CDATA[text]]></MsgType>
			<Content><![CDATA[%s]]></Content>
			</xml>";  
		$resultStr = sprintf($textTpl, $toUsername,$fromUsername,$time, $contentStr);
		echo $resultStr;
	}

	/**
	 * 回复图片信息
	 */
	static function responseImage($fromUsername,$toUsername,$mediaId){
		$time = time();
		$textTpl ="<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime><![CDATA[%s]]></CreateTime>
			<MsgType><![CDATA[image]]></MsgType>
			<Image>
			<MediaId><![CDATA[%s]]></MediaId>
			</Image>
			</xml>";  
		$resultStr = sprintf($textTpl, $toUsername,$fromUsername,$time, $mediaId);
		echo $resultStr;
	}

	/**
	 * 回复语音消息信息
	 */
	static function responseVoice($fromUsername,$toUsername,$mediaId){
		$time = time();
		$textTpl ="<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime><![CDATA[%s]]></CreateTime>
			<MsgType><![CDATA[voice]]></MsgType>
			<Voice>
			<MediaId><![CDATA[%s]]></MediaId>
			</Voice>
			</xml>";  
		$resultStr = sprintf($textTpl, $toUsername,$fromUsername,$time, $mediaId);
		echo $resultStr;
	}



	/**
	 * 回复视频消息信息
	 */
	static function responseVideo($fromUsername,$toUsername,$mediaId,$title,$description){
		$time = time();
		$textTpl ="<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime><![CDATA[%s]]></CreateTime>
			<MsgType><![CDATA[video]]></MsgType>
			<Video>
			<MediaId><![CDATA[%s]]></MediaId>
			<Title><![CDATA[%s]]></Title>
			<Description><![CDATA[%s]]></Description>
			</Video> 
			</xml>";  
		$resultStr = sprintf($textTpl, $toUsername,$fromUsername,$time, $mediaId,$title,$description);
		echo $resultStr;
	}

	/**
	 * 回复音乐消息信息
	 */
	static function responseMusic($fromUsername,$toUsername,$title,$description,$musicUrl,$hqMusicUrl,$media_id){
		$time = time();
		$textTpl ="<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime><![CDATA[%s]]></CreateTime>
			<MsgType><![CDATA[music]]></MsgType>
			<Music>
			<Title><![CDATA[%s]]></Title>
			<Description><![CDATA[%s]]></Description>
			<MusicUrl><![CDATA[%s]]></MusicUrl>
			<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
			<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
			</Music>
			</xml>";  
		$resultStr = sprintf($textTpl, $toUsername,$fromUsername,$time, $title,$description,$musicUrl,$hqMusicUrl,$media_id);
		echo $resultStr;
	}

	/**
	 * 回复音乐消息信息
	 */
	static function responseNews($fromUsername,$toUsername,$datas=array()){
		$time = time();
		$item = "";
		$textTpl ="<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime><![CDATA[%s]]></CreateTime>
			<MsgType><![CDATA[news]]></MsgType>
			<ArticleCount>".count($data)."</ArticleCount>
			<Articles>";
		$textTpl = sprintf($textTpl, $toUsername,$fromUsername,$time);
		foreach ($datas as $data) {
			$item ="<item>
				<Title><![CDATA[%s]]></Title> 
				<Description><![CDATA[%s]]></Description>
				<PicUrl><![CDATA[%s]]></PicUrl>
				<Url><![CDATA[%s]]></Url>
				</item>";
			$item = sprintf($item, $data['title'],$data['description'],$data['picUrl'], $data['url']);
			$textTpl .= $item;
		}
		$textTpl .="</Articles>
			</xml>"; 
		$resultStr = sprintf($textTpl, $toUsername,$fromUsername,$time, $title,$description,$musicUrl,$hqMusicUrl,$media_id);
		echo $resultStr;
	}


	/**
	 * 上传媒体文件
	 * $type 分别有图片（image）、语音（voice）、视频（video）和缩略图（thumb）
	 */
	static function https_upload($filePath,$access_token,$type)
	{
		$url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=".$access_token."&type=".$type;
		$data = array("file1"  => "@".$filePath);
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		if (!empty($data)){
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
	}

	/**
	 * 下载媒体文件
	 */
	static function https_download($access_token,$media_id,$fileName)
	{
		$url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$media_id;
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$package = curl_exec($ch);
		$httpinfo = curl_getinfo($ch);
		curl_close($ch);
		$imageAll = array_merge(array('header' => $httpinfo), array('body' => $package));
		weiUtil::saveWeixinFile($fileName, $imageAll["body"]);
		return $imageAll;
	}

	static function saveWeixinFile($filename, $filecontent)
	{
		$local_file = fopen($filename, 'w');
		if (false !== $local_file){
			if (false !== fwrite($local_file, $filecontent)) {
				fclose($local_file);
			}
		}
	}
	
	
	static function responseMsg(){
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
      	//extract post data
		if (!empty($postStr)){
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $time = time();
                $msgtype =$postObj->MsgType;
                $event =$postObj->Event;
                //维度
                $latitude =$postObj->Latitude;
                //经度
                $longitude =$postObj->Longitude;
                //地理位置信息
                $Label =$postObj->Label;
                
		}else{
			//欢迎关注  贸易
			
			
			
		}
	}

}
?>